<template>
  <div id="app">
    <!-- Header -->
    <header class="header can-sticky">
      <el-row type="flex" justify="space-between" align="middle" class="container">
        <el-col :span="4">
          <div class="logo">
            <a href="/home">
              <img src="@/assets/images/logo.png" alt="logo" />
            </a>
          </div>
        </el-col>
        <el-col :span="16">
          <nav class="navigation">
            <ul class="main-menu">
              <li
                v-for="(item, index) in mainMenu"
                :key="index"
                class="menu-item"
                :class="{ 'menu-item-has-children': !!item.children }"
              >
                <a :href="item.href" @click="handleMenuClick(item, $event)">
                  {{ item.title }}
                </a>

                <!-- 二级菜单 -->
                <ul v-if="item.children" class="sub-menu">
                  <li
                    v-for="(child, childIdx) in item.children"
                    :key="childIdx"
                    class="menu-item"
                    :class="{ 'menu-item-has-children': !!child.children }"
                  >
                    <a :href="child.href" @click="handleMenuClick(child, $event)">
                      {{ child.title }}
                    </a>

                    <!-- 三级菜单 -->
                    <ul v-if="child.children" class="sub-menu">
                      <li
                        v-for="(grandChild, gIdx) in child.children"
                        :key="gIdx"
                        class="menu-item"
                      >
                        <a :href="grandChild.href">{{ grandChild.title }}</a>
                      </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </nav>
        </el-col>
<!--        <el-col :span="4" class="text-right">-->
<!--          <a href="/login" class="header_btn thm-btn btn-rounded btn-small">Log In</a>-->
<!--        </el-col>-->
      </el-row>
    </header>

    <!-- Subheader  -->
    <div class="section-bg section-padding subheader">
      <el-container>
        <el-main>
          <div class="container">
            <el-row type="flex" justify="center">
              <el-col :span="24" class="text-center">
                <h1 class="text-white page-title">Blog Grid Left</h1>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
    </div>

    <!-- Blog -->
    <div class="section-padding">
      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="360px" class="sidebar">
          <!-- 搜索 -->
          <el-card class="widget mb-4">
            <div slot="header">
              <span class="widget-title">搜索</span>
            </div>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索关键词..."
              @keyup.enter.native="handleSearch"
              class="mb-2"
            >
              <el-button slot="suffix" icon="el-icon-search" @click="handleSearch"></el-button>
            </el-input>
          </el-card>

          <!-- 分类 -->
<!--          <el-card class="widget mb-4">-->
<!--            <div slot="header">-->
<!--              <span class="widget-title">分类</span>-->
<!--            </div>-->
<!--            <ul class="categories">-->
<!--              <li v-for="cat in blogList" :key="cat.clientType">-->
<!--                <a href="javascript:void(0)" @click="filterByCategory(cat.clientType)">-->
<!--                  {{ cat.clientType }} <span>({{ cat.count }})</span>-->
<!--                </a>-->
<!--              </li>-->
<!--            </ul>-->
<!--          </el-card>-->

          <!-- 最新文章 -->
          <el-card class="widget mb-4">
            <div slot="header">
              <span class="widget-title">最新文章</span>
            </div>
            <ul class="recent-post">
              <li v-for="blog in recentPosts" :key="blog.id" class="post-item">
                <div class="post-thumb">
                  <img :src="fixImgUrl(blog.coverImage)" class="image-fit" alt="img" />
                </div>
                <div class="post-caption">
                  <h6 class="post-title">
                    <a href="javascript:void(0)" @click="goToPost(blog.id)">{{ blog.title }}</a>
                  </h6>
                  <p class="post-date">{{ blog.createdAt }}</p>
                </div>
              </li>
            </ul>
          </el-card>

          <!-- 标签云 -->
<!--          <el-card class="widget">-->
<!--            <div slot="header">-->
<!--              <span class="widget-title">标签</span>-->
<!--            </div>-->
<!--            <div class="tags-cloud">-->
<!--              <el-tag-->
<!--                v-for="tag in tags"-->
<!--                :key="tag"-->
<!--                size="small"-->
<!--                class="tag-item"-->
<!--                @click.native="searchByTag(tag)"-->
<!--                style="cursor: pointer; margin: 4px;"-->
<!--              >-->
<!--                {{ tag }}-->
<!--              </el-tag>-->
<!--            </div>-->
<!--          </el-card>-->
        </el-aside>

        <!-- 主内容区 -->
        <el-main>
          <el-row :gutter="20">
            <el-col
              :xs="24"
              :sm="12"
              :md="12"
              :lg="12"
              v-for="blog in blogList"
              :key="blog.id"
              class="mb-4"
            >
              <el-card class="post-card" shadow="hover">
                <div class="post-image">
                  <img :src="fixImgUrl(blog.coverImage)" class="image-fit" alt="img" @click="goToPost(blog.id)" style="cursor: pointer;" />
                </div>
                <div class="post-caption">
                  <div class="post-date">{{ blog.createdAt }}</div>
                  <h2 class="post-title">
                    <a href="javascript:void(0)" @click="goToPost(blog.id)">{{ blog.title }}</a>
                  </h2>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import {listCases} from "@/api/achievement/cases";

export default {
  name: "blog-grid-left",
  data() {
    return {
      loading: false,
      error: null,
      searchKeyword: '',
      categories: [],
      tags: [],
      blogList: [],
      recentPosts: [],
      mainMenu: [
        {
          title: '首页',
          href: '/home'
        },
        {
          title: '关于',
          href: '/about'
        },
        {
          title: '服务',
          href: '/services',
        },
        {
          title: '博客',
          href: '#',
          children: [
            {
              title: '博客网络',
              href: '#',
              children: [
                { title: '全宽', href: '/blog-grid' },
                { title: '左侧边栏', href: '/blog-grid-left' },
                { title: '右侧边栏', href: '/blog-grid-right' }
              ]
            },
          ]
        },
        {
          title: '联系我们',
          href: '/contact'
        }
      ]
    };
  },
  mounted() {
    this.fetchRecentPosts(); // 单独加载最新文章
    this.fetchBlogList();    // 加载主列表（可带分页）
  },
  methods: {
    // 单独获取最新文章（固定前3条）
    fetchRecentPosts() {
      const params = {
        type: 'project',
        isPublished: 1,
        pageSize: 20
      };
      listCases(params)
        .then(response => {
          let posts = response.rows || [];

          // 前端强制排序兜底
          posts.sort((a, b) => {
            return new Date(b.createdAt) - new Date(a.createdAt);
          });

          this.recentPosts = posts.slice(0,3);
        })
        .catch(error => {
          console.error('加载最新文章失败:', error);
          this.recentPosts = [];
        });
    },
    // 搜索功能：只更新 blogList，不影响 recentPosts
    handleSearch() {
      const keyword = this.searchKeyword.trim();
      if (!keyword) {
        this.$message.warning('请输入搜索关键词');
        return;
      }
      this.fetchSearchResults(keyword);
    },

    fetchSearchResults(keyword) {
      this.loading = true;
      const params = {
        type: 'project',
        title: keyword,   // 或 name、content 等字段
        pageSize: 10
      };

      listCases(params)
        .then(response => {
          this.blogList = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;

          if (this.blogList.length === 0) {
            this.$message.info('未找到匹配案例');
          } else {
            this.$message.success(`找到 ${this.blogList.length} 个案例`);
          }
        })
        .catch(error => {
          console.error('搜索失败:', error);
          this.$message.error('搜索失败，请检查网络');
          this.loading = false;
        });
    },
    filterByCategory(category) {
      console.log('Filter by category:', category);
    },
    searchByTag(tag) {
      console.log('Search by tag:', tag);
    },
    goToPost(id) {
      // this.$message.info('View post ' + id);
      // 实际项目中跳转详情页
      this.$router.push(`/blog-details/${id}`)
    },
    fixImgUrl(path) {
      if (!path) return '';
      return path.startsWith(process.env.VUE_APP_BASE_API) ? encodeURI(path) : encodeURI(process.env.VUE_APP_BASE_API + path);
    },
    fetchBlogList() {
      this.loading = true; // 开启加载状态
      const params = {
        pageSize: 10,
        type: 'project',
        isPublished: 1,
        sortBy: 'createdAt',
        order: 'desc'
      };
      listCases(params).then(response => {
          console.log('API 返回数据:', response);

        let posts = response.rows || [];

        // 前端排序兜底
        posts.sort((a, b) => {
          return new Date(b.createdAt) - new Date(a.createdAt);
        });

        this.blogList = posts;
        this.total = response.total;
        this.loading = false;
        })
        .catch(error => {
          console.error('获取博客列表失败:', error);
          this.loading = false;
        });
    },
  }
};
</script>

<style scoped>
/* 全局重置与字体 */
#app {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
}

/* 容器居中，类似 Bootstrap */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* =============
   Header 样式
============= */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 0;
  position: relative;
  z-index: 1000;
}

.header.can-sticky {
  position: sticky;
  top: 0;
  transition: all 0.3s ease;
}

.logo img {
  height: 50px;
  transition: all 0.3s ease;
}

.logo img:hover {
  opacity: 0.9;
}

/* 导航栏 - 主菜单 */
.navigation {
  display: flex;
  justify-content: center;
}

.main-menu {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 30px;
  align-items: center;
}

.main-menu > .menu-item {
  position: relative;
}

.main-menu > .menu-item > a {
  text-decoration: none;
  color: #333;
  font-weight: 500;
  font-size: 16px;
  transition: color 0.3s ease;
  padding: 5px 0;
  display: block;
}

.main-menu > .menu-item > a:hover,
.main-menu > .menu-item > a.active {
  color: #0066ff;
}

/* 二级菜单 */
.sub-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: #fff;
  min-width: 200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  opacity: 0;
  visibility: hidden;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  list-style: none;
  margin: 0;
  padding: 10px 0;
  z-index: 1001;
}

.menu-item-has-children:hover > .sub-menu {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.sub-menu .menu-item {
  padding: 0;
}

.sub-menu .menu-item > a {
  color: #555;
  padding: 10px 20px;
  font-size: 15px;
  display: block;
  transition: background 0.3s ease, color 0.3s ease;
}

.sub-menu .menu-item > a:hover {
  background-color: #f5f9ff;
  color: #0066ff;
  padding-left: 24px;
}

/* 三级菜单 */
.sub-menu .sub-menu {
  left: 100%;
  top: 5px;
}

/* 登录按钮 */
.header_btn {
  background-color: #0066ff;
  color: #fff !important;
  padding: 10px 20px;
  text-decoration: none;
  border-radius: 30px;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: inline-block;
  border: none;
  outline: none;
}

.header_btn:hover {
  background-color: #0052cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 102, 255, 0.3);
}

/* =============
   Subheader 样式
============= */
.subheader {
  background-image: url('https://images.unsplash.com/photo-1499750310107-5fef28a66643?ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 100px 0;
  color: #fff;
  position: relative;
}

.subheader::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6); /* 深色遮罩提升文字可读性 */
  z-index: 1;
}

.subheader .el-main {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  letter-spacing: -0.5px;
}

.text-white {
  color: #ffffff;
}

.text-center {
  text-align: center;
}

/* =============
   响应式设计
============= */
@media (max-width: 992px) {
  .main-menu {
    gap: 20px;
  }

  .page-title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 12px 0;
  }

  .logo img {
    height: 40px;
  }

  .main-menu {
    gap: 15px;
    flex-wrap: wrap;
    justify-content: center;
  }

  .main-menu > .menu-item {
    font-size: 14px;
  }

  .sub-menu {
    min-width: 180px;
  }

  .sub-menu .menu-item > a {
    padding: 8px 16px;
    font-size: 14px;
  }

  .page-title {
    font-size: 2rem;
  }

  .container {
    padding: 0 15px;
  }
}

@media (max-width: 576px) {
  .main-menu {
    gap: 10px;
    font-size: 14px;
  }

  .header_btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .page-title {
    font-size: 1.8rem;
  }
}

/* 基本样式 */
.section-padding {
  padding: 60px 0;
}

.widget .widget-title {
  font-weight: 600;
  font-size: 18px;
}

/* 分类列表 */
.categories {
  list-style: none;
  padding: 0;
  margin: 0;
}
.categories li {
  margin-bottom: 10px;
}
.categories a {
  color: #333;
  text-decoration: none;
  font-size: 14px;
}
.categories a:hover {
  color: #409eff;
}
.categories span {
  float: right;
  color: #999;
}

/* 最新文章 */
.recent-post {
  list-style: none;
  padding: 0;
  margin: 0;
}
.post-item {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
}
.post-thumb {
  width: 60px;
  height: 60px;
  overflow: hidden;
  margin-right: 10px;
}
.post-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.post-caption {
  flex: 1;
}
.post-title {
  margin: 0;
  font-size: 14px;
  line-height: 1.4;
}
.post-title a {
  color: #333;
  text-decoration: none;
}
.post-title a:hover {
  color: #409eff;
}
.post-date {
  margin: 5px 0 0;
  color: #999;
  font-size: 12px;
}

/* 标签云 */
.tags-cloud {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

/* 文章卡片 */
.post-card {
  border-radius: 8px;
  overflow: hidden;
}
.post-image img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  transition: transform 0.3s;
}
.post-image img:hover {
  transform: scale(1.05);
}
.post-caption {
  padding: 15px;
}
.post-title {
  font-size: 16px;
  margin: 10px 0 0;
  line-height: 1.4;
}
.post-title a {
  color: #333;
  text-decoration: none;
  font-weight: 500;
}
.post-title a:hover {
  color: #409eff;
}
.post-date {
  color: #999;
  font-size: 12px;
}

/* 响应式间距 */
.mb-4 {
  margin-bottom: 1.5rem !important;
}
</style>
